package com.translate;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Administrator on 2018/1/18.
 */
@Component()
@Slf4j
public class Excel2007WriterImpl extends Excel2007Writer {

    @Override
    public void generate(List<Map<String, Object>> faildList, List<Map<String, Object>> mappingField) throws Exception {
        AtomicInteger rowIndex = new AtomicInteger(1);
        beginSheet();
        createTitle(mappingField);
        createRows(faildList, mappingField,rowIndex);
        //电子表格结束
        endSheet();
    }

    /**
     * 创建数据行
     *
     * @param results
     * @param titleList
     * @throws ParseException
     * @throws IOException
     */
    public void createRows(List<Map<String, Object>> results, List<Map<String, Object>> titleList,AtomicInteger rowIndex) {
        for (Map<String, Object> dataMap : results) {
            int cellIndex = 0;
            try {
                insertRow(rowIndex.intValue());
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (Map<String, Object> map : titleList) {
                try {
                    createCell(cellIndex, getMapValue(dataMap, map.get("fieldName").toString()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                cellIndex++;
            }
            rowIndex.incrementAndGet();
            try {
                endRow();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建标题
     *
     * @param mappingField
     * @throws IOException
     */
    public void createTitle(List<Map<String, Object>> mappingField) {
        int cell = 0;
        try {
            insertRow(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Map<String, Object> map : mappingField) {
            try {
                createCell(cell, map.get("sourceField").toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            cell++;
        }
        //结束行
        try {
            endRow();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Map获取Null情况处理
     *
     * @param map
     * @param column
     * @return
     */
    private String getMapValue(Map<String, Object> map, String column) {
        Object str = map.get(column);
        if (str == null || str == "") {
            return "";
        } else {
            return str.toString().replace("\"", "");
        }
    }
}
